<template>
  <div class="Container">
    <Header></Header>
    <div class="d-flex">
      <div class="file ml-4 mr-4">
        <v-skeleton-loader
          v-if="loadingFolderList"
          height="calc(100% - 40px)"
          tile
          type="list-item@20"
        ></v-skeleton-loader>
        <Folder
          v-else
          @add="openNewFolderDialog"
          @edit="openEditFolderDialog"
          @delete="openDeleteFolderDialog"
          @download="downloadFolder"
          v-model="activatedFolder"
          :folderList="folderList"
          :sortByValue.sync="sortByValue"
          :sortDescValue.sync="sortDescValue"
        ></Folder>
      </div>
      <div class="file-item mr-4">
        <File
          :items="fileList"
          :currentFolder="activatedFolder"
          :sortByValue.sync="sortByValue"
          :sortDescValue.sync="sortDescValue"
        ></File>
      </div>
    </div>
    <Dialog
      v-model="showDialog"
      @submit="saveFolder"
      :title="dialogTitle"
      :show-save="step !== 3"
      width="480"
    >
      <template>
        <NewFolder v-if="[1, 2].includes(step)" ref="newFolder"></NewFolder>
        <Delete
          v-else-if="step === 3"
          @delete="deleteFolder(selectedFolder)"
          title="Are you sure to delete this folder?"
          :subtitle="deleteSubtitle"
        ></Delete>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import Header from "@/components/Library/Header/Header.vue";
import NewFolder from "@/components/Library/Dialog/NewFolder/NewFolder.vue";
import Folder from "@/components/Library/Folder/Folder.vue";
import File from "@/components/Library/File/File.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import Delete from "@/components/Customer/Dialog/Delete/Delete.vue";
import { IFolder } from "@/components/Library/index";
import { getTime, getCurrentEnMonth } from "@/common/constants/Utils";
@Component({
  components: {
    Header,
    Folder,
    File,
    NewFolder,
    Dialog,
    Delete,
  },
})
export default class Library extends Vue {
  get sortByValue() {
    return this.$store.state.LibraryStore.sortByValue;
  }
  set sortByValue(value: string) {
    this.$store.commit("setSortByValue", value);
  }
  get sortDescValue() {
    return this.$store.state.LibraryStore.sortDescValue;
  }
  set sortDescValue(value: boolean | null | undefined) {
    if (value === undefined) {
      this.$store.commit("setSortDescValue", null);
      return;
    }
    this.$store.commit("setSortDescValue", value);
  }
  // 1.Add Folder 2.Edit Folder 3.Delete Folder
  step = -1;
  // dialog
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // folder
  selectedFolder: IFolder | null = null;
  activatedFolder: IFolder | null = null;
  get loadingFolderList() {
    return this.$store.state.LibraryStore.loadingFolderList;
  }

  get folderList(): IFolder[] {
    return this.$store.state.LibraryStore.folderList;
  }
  @Watch("folderList")
  onFolderListChange(folderList: IFolder[]) {
    if (folderList.length) {
      this.activatedFolder = folderList[0];
    }
  }

  getFolderList() {
    this.$store.dispatch("refreshFolderList");
  }
  // file
  get fileList() {
    if (this.activatedFolder) {
      const fileList = [...this.activatedFolder.fileList];
      if (this.activatedFolder.children) {
        fileList.push(...this.activatedFolder.children);
      }
      return fileList;
    } else {
      return [];
    }
  }
  // action
  openNewFolderDialog() {
    this.step = 1;
    this.dialogTitle = "New Folder";
    this.$nextTick(() => {
      console.log(this.$refs.newFolder);
      (this.$refs.newFolder as NewFolder).resetForm();
    });
    this.openDialog();
  }
  openEditFolderDialog(folder: IFolder) {
    this.step = 2;
    this.dialogTitle = "Edit Folder";
    this.selectedFolder = folder;
    this.$nextTick(() => {
      const NewFolderRef = this.$refs.newFolder as NewFolder;
      NewFolderRef.resetForm();
      setTimeout(() => {
        NewFolderRef.setFormData(folder.name);
      });
    });
    this.openDialog();
  }
  get deleteSubtitle() {
    if (this.selectedFolder) {
      return this.selectedFolder.name;
    } else {
      return "";
    }
  }
  openDeleteFolderDialog(folder: IFolder) {
    this.step = 3;
    this.dialogTitle = "Delete Folder";
    this.selectedFolder = folder;
    this.openDialog();
  }
  async saveFolder() {
    const result = await (this.$refs.newFolder as NewFolder).validateFormData();
    if (result) {
      if (this.step === 1) {
        this.addFolder(result);
      } else if (this.step === 2) {
        this.editFolder(result);
      }
      this.closeDialog();
    }
  }
  addFolder(folderName: string) {
    if (folderName) {
      const date = new Date();
      const modifiedDate = `${getCurrentEnMonth()} ${date.getDate()}, ${date.getFullYear()} ${getTime(
        ":"
      )}`;
      const folder = {
        id: `${new Date().getTime()}`,
        type: "Folder",
        size: "0",
        fileLocation: "",
        fileList: [],
        modifiedDate: modifiedDate,
        name: folderName,
      };
      if (this.activatedFolder) {
        if (this.activatedFolder.children) {
          this.activatedFolder.children.push(folder);
        } else {
          this.$set(this.activatedFolder, "children", [folder]);
        }
      } else {
        this.folderList.push(folder);
      }
    }
  }

  editFolder(folderName: string) {
    if (this.activatedFolder) {
      this.activatedFolder.name = folderName;
    }
  }

  deleteFolder(folder: IFolder | null) {
    if (folder) {
      const index = this.folderList.findIndex((item) => folder.id === item.id);
      if (index >= 0) {
        this.folderList.splice(index, 1);
      } else {
        const parent = this.getParent(this.folderList, folder.id as string);
        if (parent) {
          const children = parent.children as IFolder[];
          children.splice(children.indexOf(folder), 1);
        }
      }
      this.closeDialog();
    }
  }

  downloadFolder() {
    console.log("downloadFolder");
  }

  // 获取父级元素
  getParent(treeItems: IFolder[], childrenId: string): IFolder | undefined {
    for (let i = 0; i < treeItems.length; i++) {
      const treeItem = treeItems[i];
      if (treeItem.children && treeItem.children.length !== 0) {
        if (
          treeItem.children.some((child) => {
            return child.id === childrenId;
          })
        ) {
          return treeItem;
        } else {
          const parent = this.getParent(treeItem.children, childrenId);
          if (parent) {
            return parent;
          }
        }
      }
    }
    return undefined;
  }
  created() {
    this.getFolderList();
  }
}
</script>

<style lang="scss">
@import "@/views/13000000-Library/index.scss";
</style>
